import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../../app_files.dart';
import 'package:flutter/services.dart';

Effect<AccountInfoViewState> buildEffect() {
  return combineEffects(<Object, Effect<AccountInfoViewState>>{
    AccountInfoViewAction.onSubmit: _onSubmit,
    AccountInfoViewAction.onCopyNo: _onCopyNo,
    Lifecycle.initState: _initState,
  });
}

void _initState(Action action, Context<AccountInfoViewState> ctx) async {
  if (ctx.state.model != null) {
    return;
  }
  ResultData res = await CommonNetWork.gasAccountInfo(userName: ctx.state.accountName,accountNo: ctx.state.accountNo);
  if (res.success) {
    GasAccountInfoModel infoModel = GasAccountInfoModel.fromJson(res.data);
    ctx.state.model = infoModel;
    ctx.dispatch(AccountInfoViewActionCreator.onAction());
  }
  else {
    await CommonUtils.showAlertView(ctx.context, res.desc);
    Navigator.pop(ctx.context);
  }
}

void _onSubmit(Action action, Context<AccountInfoViewState> ctx) async {
  if (ctx.state.isDel) {
    var res = await CommonUtils.showOKCanceltView(ctx.context, '确定解除户号绑定？');
    if (res == 1) {
      CommonUtils.showLoadingDialog(ctx.context);
      ResultData res = await CommonNetWork.delBlind(
        ctx.state.blindID,
        ctx.state.accountNo,
      );
      if (res.success) {
        bus.emit('refreshAccountList');
        Navigator.pop(ctx.context);
        Navigator.pop(ctx.context);
      }
      else {
        CommonUtils.showErrorInfo(ctx.context, res.desc);
      }

    }
    return;
  } else {
    var res = await CommonUtils.showOKCanceltView(ctx.context, '确定绑定户号？');
    if (res == 1) {
      CommonUtils.showLoadingDialog(ctx.context);
      await Future.delayed(Duration(milliseconds: 300));
      bus.emit('addAccountList');
      Navigator.pop(ctx.context);
      await CommonUtils.showAlertView(ctx.context, '绑定成功！');
      Navigator.pop(ctx.context);
      Navigator.pop(ctx.context);
    }
  }
}

void _onCopyNo(Action action, Context<AccountInfoViewState> ctx) async {
  await Clipboard.setData(ClipboardData(text: ctx.state.model.accountNo));
  CommonUtils.showToast(ctx.context, '已复制到剪切板');
}
